package top.oauth2.gateway.filter;

import lombok.AllArgsConstructor;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import top.oauth2.gateway.config.IgnoreUrlsConfig;

import java.net.URI;
import java.util.List;

/**
 * @author xphu
 * @version 1.0
 * @date 2021/8/30 14:41
 */
@AllArgsConstructor
@Component
public class IgnoreUrlsRemoverJwtFilter implements WebFilter {

    private final IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        AntPathMatcher matcher = new AntPathMatcher();
        // 获取白名单
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        //白名单路径移除JWT请求头
        for (String ignoreUrl : ignoreUrls) {
            if (matcher.match(ignoreUrl, uri.getPath())){
                request = exchange.getRequest().mutate().header("Authorization", "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
    }
}
